<?php

namespace App\Http\Controllers\Admin;

use App\Admin\AdminLog;
use App\Http\Middleware\ActionLog;
use App\Models\About;
use App\Models\Admin;
use App\Models\Announcement;
use App\Models\Goods;
use App\Models\Menu;
use App\Models\Order;
use App\Models\Role;
use App\Models\RoleMenu;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class HomeController extends Controller
{

    public function home(Request $request)
    {
        $admin_id = $request->cookie('admin_id');
        $admin = Admin::find($admin_id);

        return view('admin/home',$admin);
    }

    /**
     * 首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $user_count   = User::count();
        $goods_count   = Goods::count();
        $order_count   = Order::count();
        $order_price   = Order::sum('price');

        return view('admin/index',['user_count'=>$user_count,'goods_count'=>$goods_count,'order_count'=>$order_count,'order_price'=>$order_price]);
    }

    public function getAllRoleMenu(Request $request)
    {
        $admin_id = $request->cookie('admin_id');


        $menus = Menu::get()->toArray();
        $list = [];
        foreach ($menus as $key => $menu) {
            if ($menu['id'] == 1) {
                $list[$key]['homeInfo'] = $menu;
            }
            $list[$key]['logoInfo'] = [
                'title' => '拍卖系统',
                'image' =>"/images/logo.png",
            ];


        }
        $menuInfo=[];

        if ($admin_id != 1) {
            $admin = Admin::find($admin_id);

            $menu_ids = RoleMenu::where('role_id',$admin->role_id)->pluck('menu_id')->toArray();
            if (!$menu_ids) {
                return [
                    'logoInfo' => [
                        'title' => '拍卖系统',
                        'image' => "",
                    ]
                ];

            }

            if (in_array(2, $menu_ids)) {
                $permissions = Menu::select('title', 'icon',\DB::raw( 'path as href'))->find(2)->toArray();
                if (!$permissions['href']) {
                    unset($permissions['href']);
                }

                $permissions['child'] = $this->child(2, $menu_ids);

                $menuInfo['permissions'] = $permissions;
            }


            if (in_array(1, $menu_ids)) {
                $homeInfo = Menu::select('title', 'icon',\DB::raw( 'path as href'))->find(1)->toArray();
            }else{
                $homeInfo =['title'=>'没有权限'];
            }


            $data = [
                'homeInfo' =>$homeInfo,
                'logoInfo' => [
                    'title' => '拍卖系统',
                    'image' => "/images/logo.png",
                ],

                'menuInfo' =>$menuInfo


            ];
        } else {

            $permissions = Menu::select('title', 'icon',\DB::raw( 'path as href'))->find(2)->toArray();
            if (!$permissions['href']) {
                unset($permissions['href']);
            }

            $permissions['child'] = $this->child(2);
//            dd($permissions);

            $data = [
                'homeInfo' => Menu::select('title', 'icon', \DB::raw( 'path as href'))->find(1)->toArray(),
                'logoInfo' => [
                    'title' => '拍卖系统',
                    'image' => "/images/logo.png",
                ],

                'menuInfo' => [
                    'permissions' => $permissions,
                ]


            ];
        }


//        dd($data);
        return $data;


    }

    public function child($pid, $menu_ids = array())
    {
        $permissions = Menu::where('p_id', $pid)->where(function ($query) use ($menu_ids) {
            if ($menu_ids) {
                $query->whereIn('id', $menu_ids);
            }

        })->select('id', 'title', 'icon',  \DB::raw( 'path as href'), 'target')->get()->toArray();



        $permissions_menu = [];
        foreach ($permissions as $key => $permission) {
            $permissions_menu[$key] = $permission;
//            var_dump($permission['id']);

            $child = $this->child($permission['id']);
            if ($child) {
                $permissions_menu[$key]['child'] = $child;

            }

        }

        return $permissions_menu;
    }
    /**
     * 数据统计
     */
    public function statistical()
    {
        //用户总量
        $data['user_count'] = User::count();

        //本月用户新增数据
        $data['date_user_count'] = User::whereYear('created_at', date('Y'))
            ->whereMonth('created_at', date('m'))
            ->select(\DB::raw("DATE_FORMAT('created_at','%Y-%m-%d') as  c_date,count(*) as user_count "))->groupBy('c_date')->get();

        //交易笔数
        $data['order'] = Order::count();
        $data['date_user_count'] = Order::whereYear('created_at', date('Y'))
            ->whereMonth('created_at', date('m'))
            ->select(\DB::raw("DATE_FORMAT('created_at','%Y-%m-%d') as  c_date,count(*) as order_count "))->groupBy('c_date')->get();
        //交易额
        $data['order'] = Order::sum('price');
        $data['date_user_count'] = Order::whereYear('created_at', date('Y'))
            ->whereMonth('created_at', date('m'))
            ->select(\DB::raw("DATE_FORMAT('created_at','%Y-%m-%d') as  c_date,sum(price) as order_count "))->groupBy('c_date')->get();


//        return
        return $this->success($data);
    }


    /**
     * 关于我们
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function    aboutIndex()
    {
        $about = About::find(1);
        return view('admin/about',$about);
    }

    /**
     * 关于我们
     */
    public function about()
    {
        $about = About::find(1);

        return $this->success($about);
    }

    /**
     *编辑关于我们
     */
    public function saveAbout(Request $request)
    {
        $params = $request->only(['content']);
        $validator = \Validator::make($params, [
//            'name' => 'required|exists:problems,id',
//            'phone' => 'required|string|max:100',
//            'address' => 'required',
            'content' => 'required',
//            'email' => 'required',
//            'qq' => 'required',
        ], [
//            'type_id.*' => '参数错误',
            'content.required' => '介绍必填',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $about = About::find(1);
//        $about->phone = $request->phone;
//        $about->name = $request->name;
//        $about->address = $request->address;
        $about->content = $request->get('content');
//        $about->email = $request->email;
//        $about->qq = $request->qq;
        if ($about->save()) {
            return $this->success(['msg' => '保存成功']);
        }
        return $this->error('保存失败');

    }


    /**
     *协议
     * @return \Illuminate\Http\JsonResponse
     */
    public function agreement()
    {
       $announcement = Announcement::where('tag', 'registered')->first();
        return view('admin/agreement',$announcement);
    }

    /**
     * 协议编辑
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function agreementSave(Request $request)
    {
        $params = $request->only(['title', 'content']);

        $validator = \Validator::make($params, [
            'title' => 'required|string|max:100',
            'content' => 'required',
        ], [
            'title.required' => '标题必填',
            'title.max' => '数据太长',
            'content.required' => '协议不能为空',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        try{

            $announcement = Announcement::where('tag', 'registered')->first();
            $announcement->title = $request->title;
            $announcement->content = $request->get('content');
            if($announcement->save())
            {
                return $this->success(['msg' => '保存成功']);
            }


        }catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }


    }


    /**
     * 图片上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadImg(Request $request)
    {

        //上传文件最大大小,单位M
        $maxSize = 10;
        //支持的上传图片类型
        $allowed_extensions = ["png", "jpg", "gif"];
        //返回信息json
        $data = ['code' => 200, 'msg' => '上传失败', 'data' => ''];
        $file = $request->file('file');

        //检查文件是否上传完成
        if ($file->isValid()) {
            //检测图片类型
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext), $allowed_extensions)) {
                $data['msg'] = "请上传" . implode(",", $allowed_extensions) . "格式的图片";
                return $this->error($data['msg']);
            }
            //检测图片大小
            if ($file->getClientSize() > $maxSize * 1024 * 1024) {
                $data['msg'] = "图片大小限制" . $maxSize . "M";
                return $this->error($data['msg']);
            }
        } else {
            $data['msg'] = $file->getErrorMessage();
            return response()->json($data);
        }

        $filedir = "upload/" . date('Y-m-d', time()); //2、定义图片上传路径
        $filename = md5(uniqid('image', true) . time()) . '.' . $file->getClientOriginalExtension();

        $file->move($filedir, $filename);

        $url = '/' . $filedir . '/' . $filename;

        $data = [
            'code'=>0,
            'msg' => '上传成功',
            'data' => ['src'=>$url],
            'url' => $url
        ];
//        $data=

        return $this->success($data);
    }


    /**
     * 注册协议
     * @return \Illuminate\Http\JsonResponse
     */
    public function    agreement1()
    {

        $about = Announcement::find(1);

        return $this->success($about);


    }


    /**
     * 操作记录
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public   function   operationLog()
    {

        $data['list'] =Admin::get();
        return  view('admin/log',$data);
    }

    /**
     * 记录列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function  operationLogData(Request $request)
    {
        $data = \App\Models\AdminLog::with('user')->paginate()->toArray();

        return $this->success(['data'=>$data['data'], 'count'=> $data['total'],'code'=>0]);
    }
}
